//app.js
App({
  onLaunch: function () {
    let app = this
    // 如果没有习惯数据，添加3个默认的
    let customList = wx.getStorageSync('custom_list')
    if (!customList) customList = []
    if (customList.length === 0) {
      customList = ['早起', '早睡', '健身']
      wx.setStorageSync('custom_list', customList)
    }

    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        this.apis().login(res.code, function(res) {
          console.log(res)
          app.globalData.userObject = res.data
          app.saveUserInfo(res.data.id)
        })
      }
    })
  },
  saveUserInfo (userId) {
    let app = this
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              app.globalData.userInfo = res.userInfo
              console.log(res.userInfo)

              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (app.userInfoReadyCallback) {
                app.userInfoReadyCallback(res)
              }

              if (app.userInfoReadyCallback2) {
                app.userInfoReadyCallback2(res)
              }

              // 保存用户资料到服务器
              app.globalData.userObject.name = res.userInfo.nickName
              app.globalData.userObject.avatar = res.userInfo.avatarUrl
              app.globalData.userObject.sex = res.userInfo.gender
              app.apis().updateUser(userId, app.globalData.userObject, function (res) {
                console.log('保存用户资料成功')
              })
            }
          })
        }
      }
    })
  },
  globalData: {
    userInfo: null,
    userObject: null
  },
  apiServer: 'http://daka.com:8080',
  apis: function () {
    let app = this
    return {
      login(code, success) {
        wx.request({
          url: app.apiServer + '/login/code',
          method: 'POST',
          data: {code},
          success
        })
      },
      updateUser(userId, data, success) {
        wx.request({
          url: app.apiServer + '/user/' + userId,
          method: 'PUT',
          data,
          success
        })
      },
      getArticles: function (success) {
        wx.request({
          url: app.apiServer + '/article',
          success
        })
      },
      getArticle: function (article_id, success) {
        wx.request({
          url: app.apiServer + '/article/' + article_id,
          success
        })
      },
      getCustoms: function (userId) {
        return new Promise((resolve, reject) => {
          wx.request({
            url: app.apiServer + '/custom/search/findByAndUserid?user_id=' + userId,
            success (res) {
              resolve(res.data)
            }
          })
        })
      },
      addCustom(userId, name) {
        return new Promise((resolve, reject) => {
          wx.request({
            url: app.apiServer + '/custom',
            method: 'POST',
            data: {
              userid: userId,
              name
            },
            success(res) {
              resolve(res.data)
            }
          })
        })
      },
      deleteCustom(customId) {
        return new Promise((resolve, reject) => {
          wx.request({
            url: app.apiServer + '/custom/' + customId,
            method: 'DELETE',
            success(res) {
              resolve(res)
            }
          })
        })
      },
      getCustomLogs: function (userId, date) {
        return new Promise((resolve, reject) => {
          wx.request({
            url: app.apiServer + '/custom_logs/search/findByDateAndUserid?user_id=' + userId + '&date=' + date + '&sort=date,desc',
            success(res) {
              resolve(res.data)
            }
          })
        })
      },
      addCustomLog(userId, date, custom) {
        return new Promise((resolve, reject) => {
          wx.request({
            url: app.apiServer + '/custom_logs',
            method: 'POST',
            data: {
              userid: userId,
              date: date,
              custom
            },
            success (res) {
              resolve(res.data)
            }
          })
        })
      },
      updateCustomLog(customLogId, data) {
        return new Promise((resolve, reject) => {
          wx.request({
            url: app.apiServer + '/custom_logs/' + customLogId,
            method: 'PUT',
            data,
            success(res) {
              resolve(res.data)
            }
          })
        })
      },
      deleteCustomLog(customLogId) {
        return new Promise((resolve, reject) => {
          wx.request({
            url: app.apiServer + '/custom_logs/' + customLogId,
            method: 'DELETE',
            success(res) {
              resolve(res)
            }
          })
        })
      },
      getWeightLogs: function (userId) {
        return new Promise((resolve, reject) => {
          wx.request({
            url: app.apiServer + '/weight_logs/search/findByUserid?user_id=' + userId + '&sort=date,desc',
            success(res) {
              resolve(res.data)
            }
          })
        })
      },
      addWeightLog(userId, date, weight) {
        return new Promise((resolve, reject) => {
          wx.request({
            url: app.apiServer + '/weight_logs',
            method: 'POST',
            data: {
              userid: userId,
              date,
              weight
            },
            success(res) {
              resolve(res.data)
            }
          })
        })
      },
    }
  }
})